//
// Created by 19693 on 2023/11/28.
//
#include <stdio.h>
#include <unity.h>
#include "stdlib.h"
#include "esp_log.h"
#include "driver/i2c.h"

static const char *TAG = "i2c-simple-example";

#define AHT10_MASTER_SCL_IO           8      /*!< GPIO number used for I2C master clock */
#define AHT10_MASTER_SDA_IO           9      /*!< GPIO number used for I2C master data  */
#define I2C_MASTER_NUM              0                          /*!< I2C master i2c port number, the number of i2c peripheral interfaces available will depend on the chip */
#define I2C_MASTER_FREQ_HZ          400000                     /*!< I2C master clock frequency */
#define I2C_MASTER_TX_BUF_DISABLE   0                          /*!< I2C master doesn't need buffer */
#define I2C_MASTER_RX_BUF_DISABLE   0                          /*!< I2C master doesn't need buffer */
#define I2C_MASTER_TIMEOUT_MS       1000

/**
 * @brief i2c master initialization
 */
static esp_err_t aht10_config_init(void) {
    int i2c_master_port = I2C_MASTER_NUM;

    i2c_config_t conf = {
            .mode = I2C_MODE_MASTER,
            .sda_io_num = AHT10_MASTER_SDA_IO,
            .scl_io_num = AHT10_MASTER_SCL_IO,
            .sda_pullup_en = GPIO_PULLUP_ENABLE,
            .scl_pullup_en = GPIO_PULLUP_ENABLE,
            .master.clk_speed = I2C_MASTER_FREQ_HZ,
    };

    esp_err_t ret = i2c_param_config(i2c_master_port, &conf);
    TEST_ASSERT_EQUAL_MESSAGE(ESP_OK, ret, "I2C0 config returned error");

    return i2c_driver_install(i2c_master_port, conf.mode, I2C_MASTER_RX_BUF_DISABLE, I2C_MASTER_TX_BUF_DISABLE, 0);
}

esp_err_t aht10_init() {
    aht10_config_init();        // 引脚初始化
    uint8_t flag = 3;

    // 初始化
    i2c_master_read_from_device(I2C_MASTER_NUM, 0x38, &flag, 1, 1000 / portTICK_PERIOD_MS);
    printf("aht10 init: %d\r\n", ((flag & 0x08) >> 3));
    // 没有初始化成功，则使用下面的代码
//    if (((flag & 0x08) >> 3) != 1) {
//        HAL_I2C_Master_Transmit(&hi2c1, 0x70, (uint8_t *) sendata, 3, 1000);
//    }
    return flag;
}

void ReadData(float *temperature, uint32_t *humidity) {
    uint8_t triger[3] = {0xac, 0x33, 0x00};         // AC

    // 触发测量
    i2c_master_write_to_device(0, 0x38, (uint8_t *) triger, 3, pdMS_TO_TICKS(1000));
    vTaskDelay(pdMS_TO_TICKS(80));

    // 读取数据
    uint8_t data_buffer[6] = {0};
    ESP_ERROR_CHECK(i2c_master_read_from_device(0, 0x38, (uint8_t *) data_buffer, 6, pdMS_TO_TICKS(1000)));
    char str[50];
//    sprintf(str,"%02X%02X%02X%02X%02X%02X",data_buffer[0],data_buffer[1],data_buffer[2],data_buffer[3],data_buffer[4],data_buffer[5]);
//    printf("ahtbuffer:%s\r\n",str);

    uint32_t SRH = (data_buffer[1] << 12) + (data_buffer[2] << 4) + (data_buffer[3] >> 4);
    *humidity = (int) (SRH * 1000.0 / 1024 / 1024);

    // 温度
    uint32_t ST = ((data_buffer[3] & 0X0f) << 16) + (data_buffer[4] << 8) + (data_buffer[5]);
    *temperature = ((int) (ST * 2000.0 / 1024 / 1024)) - 500;
}
